#include "Backup.h"
#include <stdio.h>
#include <fstream>
#include <string>
#include <ios>

Backup::Backup(const char* fileName) : m_FileName(fileName)
{
  std::cout << ">>>> Backup constructor  " << this << std::endl;
}

void Backup::makeDataBackupFile(const char* i_data)
{
  FILE *temp_file = nullptr;
  fopen_s(&temp_file, "data_to_write.df", "w");
  if (i_data != NULL)
  {
    fputs(i_data, temp_file);
    fclose(temp_file);
  }
}

void Backup::makeBackupFile(const char* i_file_name)
{
  char data[100];
  FILE *mf = nullptr;
  fopen_s(&mf, i_file_name, "r");
  if (mf == NULL) perror("Error opening file! File doesnt exist.");
  else
  {
    fgets(data, 100, mf);
    fclose(mf);
  }
  FILE *backup_file = nullptr;
  fopen_s(&backup_file, "temp_file.tmpfl", "w");
  if (data != NULL)
  {
    fputs(data, backup_file);
    fclose(backup_file);
  }
}

int Backup::writeToFile(const char* i_data)
{
  FILE *mainfile = nullptr;
  const char* mainfile_filename = "mainfile.mf";
  makeBackupFile(m_FileName);
  int size = 0;
  fopen_s(&mainfile, mainfile_filename, "w");
  if (mainfile != NULL)
  {
    size = sizeof(i_data);
    makeDataBackupFile(i_data);
    fputs(i_data, mainfile);
    fclose(mainfile);
  }
  return size;
}